package com.example.cardgame
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.GridLayout
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.example.cardgame.model.CardMatchingGame
class MainActivity : AppCompatActivity(), View.OnClickListener {

    lateinit var game: CardMatchingGame
    val cardButtons = mutableListOf<Button>()
    lateinit var TextView: TextView
    lateinit var sharedPreferences: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE)
        TextView = findViewById<TextView>(R.id.textView1)


        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)
        for (i in 0 until gridLayout.childCount) {
            val v = gridLayout.getChildAt(i)
            if (v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        val reset = findViewById<Button>(R.id.reset)
        reset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }


        val exit = findViewById<Button>(R.id.exit)
        exit.setOnClickListener {
            saveHighScore()
            val intent = Intent(this, FirstActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

    fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor( android.graphics.Color.WHITE)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.card)
            }
        }
        TextView.text = "Score: ${game.score}"
    }


    override fun onClick(v: View?) {
        if (v is Button) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }


    private fun saveHighScore() {
        val editor = sharedPreferences.edit()
        val currentHighScore = sharedPreferences.getInt("highScore", 0)
        if (game.score > currentHighScore) {
            editor.putInt("highScore", game.score)
            editor.apply()
        }
    }



}